using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;

namespace PhotoBlenderLib {
	class PixelStorage {

		private Color[,] colors;
        private int[,] pixelcount;
		private int _width = 0;
		private int _height = 0;
		//private int count = 0;

		/// <summary>
		/// Create new instance of PixelStorage
		/// </summary>
		/// <param name="width">Photo width</param>
		/// <param name="height">Photo height</param>
		public PixelStorage(int width, int height) {
			// set width and height
			_width = width;
			_height = height;

			colors = new Color[_width, _height];
            pixelcount = new int[_width, _height];

			// set an initial color
			for (int x = 0; x < _width; x++) {
				for (int y = 0; y < _height; y++) {
					colors[x, y] = Color.Gray;
                    pixelcount[x, y] = 0;
				}
			}
		}


		/// <summary>
		/// Add image to include in the average
		/// </summary>
		/// <param name="bmp">Image to include in the average</param>
		public void AddAverage(Bitmap bmp) {
			//count++;
            Color currentColor;
			for (int x = 0; x < _width; x++) {
				for (int y = 0; y < _height; y++) {
                    currentColor = bmp.GetPixel(x, y);
                    if (currentColor != Color.FromArgb(128,128,128))
                    {
                        //pixelcount[x, y]++;
                        colors[x, y] = AverageColor(colors[x, y], currentColor, ++pixelcount[x,y]);
                    }
				}
			}
		}


		private Color AverageColor(Color current, Color next, int count) {
			int R = AverageChannel(current.R, next.R, count);
			int G = AverageChannel(current.G, next.G, count);
			int B = AverageChannel(current.B, next.B, count);

			return Color.FromArgb(R, G, B);
		}


        private int AverageChannel(int current, int next, int count)
        {
			current = current * (count - 1);
			current += next;
			current = (int)((double)current / (double)count);
			return current;
		}

		/// <summary>
		/// Get the averaged photo
		/// </summary>
		/// <returns>Bitmap of averaged photo</returns>
		public Bitmap GetAveragePhoto() {
			Bitmap bmp = new Bitmap(_width, _height);
			for (int x = 0; x < _width; x++) {
				for (int y = 0; y < _height; y++) {
					bmp.SetPixel(x, y, colors[x,y]);
				}
			}
			return bmp;
		}

	}
}
